package com.example.spgl.controller;

import com.example.spgl.entity.Result;
import com.example.spgl.service.FileService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/file")
@CrossOrigin(origins = "http://localhost:5173") // 允许特定来源地址跨域请求
public class FileController {
    @Autowired
    private FileService fileService;


    /**
     * 批量文件上传接口
     */
    @RequestMapping("/uploadList")
    public Result uploadBatch(@RequestParam("imageList") List<MultipartFile> fileList) throws IOException {
        ArrayList<String> ans = new ArrayList<>();
        for(MultipartFile file : fileList){
            String url = fileService.uploadFile(file, UUID.randomUUID().toString().substring(0,20)+"-"+file.getOriginalFilename());
            ans.add(url);
        }
        return Result.success(ans);
    }

    /**
     * 上传接口
     */
    @RequestMapping("/upload")
    public Result upload(@RequestParam("image") MultipartFile file) throws IOException{
        String url = fileService.uploadFile(file,UUID.randomUUID().toString().substring(0,20)+"-"+file.getOriginalFilename());
        return Result.success(url);
    }

    /**
     * 下载接口
     */
    @RequestMapping("/download/{fileName}")
    public void download(@PathVariable("fileName") String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
        fileService.downloadFile(fileName,request,response);
    }

    /**
     * 删除接口
     */
    @RequestMapping("/delete")
    public Result deleteFile(@RequestParam String fileName){
        boolean flag = fileService.deleteFile(fileName);
        return Result.success(flag);
    }

}
